/**
 * Copyright &copy; 2012-2016 <a href="https://github.com/thinkgem/jeesite">JeeSite</a> All rights reserved.
 */
package com.thinkgem.jeesite.modules.sys.service;

import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.*;

import com.thinkgem.jeesite.common.utils.Reflections;
import com.thinkgem.jeesite.common.utils.excel.annotation.ExcelField;
import com.thinkgem.jeesite.modules.classgroup.dao.ClassGroupDao;
import com.thinkgem.jeesite.modules.classgroup.entity.ClassGroup;
import com.thinkgem.jeesite.modules.sys.dao.OfficeDao;
import org.activiti.engine.IdentityService;
import org.activiti.engine.identity.Group;
import org.apache.ibatis.annotations.Param;
import org.apache.shiro.session.Session;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.thinkgem.jeesite.common.config.Global;
import com.thinkgem.jeesite.common.persistence.Page;
import com.thinkgem.jeesite.common.security.Digests;
import com.thinkgem.jeesite.common.security.shiro.session.SessionDAO;
import com.thinkgem.jeesite.common.service.BaseService;
import com.thinkgem.jeesite.common.service.ServiceException;
import com.thinkgem.jeesite.common.utils.CacheUtils;
import com.thinkgem.jeesite.common.utils.Encodes;
import com.thinkgem.jeesite.common.utils.StringUtils;
import com.thinkgem.jeesite.common.web.Servlets;
import com.thinkgem.jeesite.modules.act.dao.ActDao;
import com.thinkgem.jeesite.modules.sys.dao.MenuDao;
import com.thinkgem.jeesite.modules.sys.dao.RoleDao;
import com.thinkgem.jeesite.modules.sys.dao.UserDao;
import com.thinkgem.jeesite.modules.sys.entity.CustomTitle;
import com.thinkgem.jeesite.modules.sys.entity.Dict;
import com.thinkgem.jeesite.modules.sys.entity.Menu;
import com.thinkgem.jeesite.modules.sys.entity.Office;
import com.thinkgem.jeesite.modules.sys.entity.Role;
import com.thinkgem.jeesite.modules.sys.entity.User;
import com.thinkgem.jeesite.modules.sys.security.SystemAuthorizingRealm;
import com.thinkgem.jeesite.modules.sys.utils.LogUtils;
import com.thinkgem.jeesite.modules.sys.utils.UserUtils;

/**
 * 系统管理，安全相关实体的管理类,包括用户、角色、菜单.
 * @author xiaoming
 * @version 2013-12-05
 */
@Service
@Transactional(readOnly = true)
public class SystemService extends BaseService implements InitializingBean {
	
	public static final String HASH_ALGORITHM = "SHA-1";
	public static final int HASH_INTERATIONS = 1024;
	public static final int SALT_SIZE = 8;
	
	@Autowired
	private UserDao userDao;
	@Autowired
	private RoleDao roleDao;
	@Autowired
	private MenuDao menuDao;
	@Autowired
	private SessionDAO sessionDao;
	@Autowired
	private OfficeDao officeDao;
	@Autowired
	private SystemAuthorizingRealm systemRealm;
	
	@Autowired
	private ActDao actDao;
	
	public SessionDAO getSessionDao() {
		return sessionDao;
	}

	@Autowired
	private IdentityService identityService;

	@Autowired
	protected ClassGroupDao classGroupDao;

	//-- User Service --//
	
	/**
	 * 获取用户
	 * @param id
	 * @return
	 */
	public User getUser(String id) {
		return UserUtils.get(id);
	}
	/**
	 * 获取用户
	 * @param id
	 * @param noCache true=从数据库取   false=缓存中获取
	 * @return
	 */
	public User getUser(String id,boolean noCache) {
		if(noCache){
			return userDao.get(id);
		}else{
			return UserUtils.get(id);
		}
	}

	/**
	 * 根据登录名获取用户
	 * @param loginName
	 * @return
	 */
	public User getUserByLoginName(String loginName) {
		return UserUtils.getByLoginName(loginName);
	}
	
	public Page<User> findUser(Page<User> page, User user) {
		// 生成数据权限过滤条件（dsf为dataScopeFilter的简写，在xml中使用 ${sqlMap.dsf}调用权限SQL）
		user.getSqlMap().put("dsf", dataScopeFilter(user.getCurrentUser(), "o", "a"));
		// 设置分页参数
		user.setPage(page);
		// 执行分页查询
		page.setList(userDao.findList(user));
		return page;
	}
	
	/**
	 * 无分页查询人员列表
	 * @param user
	 * @return
	 */
	public List<User> findUser(User user){
		// 生成数据权限过滤条件（dsf为dataScopeFilter的简写，在xml中使用 ${sqlMap.dsf}调用权限SQL）
		user.getSqlMap().put("dsf", dataScopeFilter(user.getCurrentUser(), "o", "a"));
		List<User> list = userDao.findList(user);
		return list;
	}

	/**
	 * 通过部门ID获取用户列表，仅返回用户id和name（树查询用户时用）
	 * @param officeId
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public List<User> findUserByOfficeId(String officeId,String ... uType) {
		if(officeId.equals("f999c6afb205438082535b39605af12e")){
			System.out.println("啊啊啊啊啊");
		}
		String cacheKey = UserUtils.USER_CACHE_LIST_BY_OFFICE_ID_ + officeId;
		if(uType.length>0&&StringUtils.isNotBlank(uType[0]))cacheKey+=uType[0];
		List<User> list = (List<User>)CacheUtils.get(UserUtils.USER_CACHE, cacheKey);
		if (list == null){
			User user = new User();
			user.setOffice(new Office(officeId));
			if(uType.length>0&&StringUtils.isNotBlank(uType[0]))user.setuType(uType[0]);
			list = userDao.findUserByOfficeId(user);
			CacheUtils.put(UserUtils.USER_CACHE, cacheKey, list);
		}
		return list;
	}
	
	@Transactional(readOnly = false)
	public void saveUser(User user) {
		if (StringUtils.isBlank(user.getId())){
			user.preInsert();
			userDao.insert(user);
		}else{
			// 清除原用户机构用户缓存
			User oldUser = userDao.get(user.getId());
			if (oldUser.getOffice() != null && oldUser.getOffice().getId() != null){
				CacheUtils.remove(UserUtils.USER_CACHE, UserUtils.USER_CACHE_LIST_BY_OFFICE_ID_ + oldUser.getOffice().getId());
			}
			// 更新用户数据
			user.preUpdate();
			userDao.update(user);
		}
		if (StringUtils.isNotBlank(user.getId())){
			// 更新用户与角色关联
			userDao.deleteUserRole(user);
			if (user.getRoleList() != null && user.getRoleList().size() > 0){
				userDao.insertUserRole(user);
			}else{
				throw new ServiceException(user.getLoginName() + "没有设置角色！");
			}
			// 将当前用户同步到Activiti
			saveActivitiUser(user);
			// 清除用户缓存
			UserUtils.clearCache(user);
//			// 清除权限缓存
//			systemRealm.clearAllCachedAuthorizationInfo();
		}
	}
	
	@Transactional(readOnly = false)
	public void updateUserInfo(User user) {
		user.preUpdate();
		userDao.updateUserInfo(user);
		// 清除用户缓存
		UserUtils.clearCache(user);
//		// 清除权限缓存
//		systemRealm.clearAllCachedAuthorizationInfo();
	}
	
	@Transactional(readOnly = false)
	public void deleteUser(User user) {
		userDao.delete(user);
		// 同步到Activiti
		deleteActivitiUser(user);
		// 清除用户缓存
		UserUtils.clearCache(user);
//		// 清除权限缓存
//		systemRealm.clearAllCachedAuthorizationInfo();
	}
	
	@Transactional(readOnly = false)
	public void updatePasswordById(String id, String loginName, String newPassword) {
		User user = new User(id);
		user.setPassword(entryptPassword(newPassword));
		userDao.updatePasswordById(user);
		// 清除用户缓存
		user.setLoginName(loginName);
		UserUtils.clearCache(user);
//		// 清除权限缓存
//		systemRealm.clearAllCachedAuthorizationInfo();
	}
	
	@Transactional(readOnly = false)
	public void updateUserLoginInfo(User user) {
		// 保存上次登录信息
		user.setOldLoginIp(user.getLoginIp());
		user.setOldLoginDate(user.getLoginDate());
		// 更新本次登录信息
		user.setLoginIp(StringUtils.getRemoteAddr(Servlets.getRequest()));
		user.setLoginDate(new Date());
		userDao.updateLoginInfo(user);
	}
	
	/**
	 * 生成安全的密码，生成随机的16位salt并经过1024次 sha-1 hash
	 */
	public static String entryptPassword(String plainPassword) {
		String plain = Encodes.unescapeHtml(plainPassword);
		byte[] salt = Digests.generateSalt(SALT_SIZE);
		System.out.println(StringUtils.join(salt, ""));
		byte[] hashPassword = Digests.sha1(plain.getBytes(), salt, HASH_INTERATIONS);
		return Encodes.encodeHex(salt)+Encodes.encodeHex(hashPassword);
	}
	
	/**
	 * 验证密码
	 * @param plainPassword 明文密码
	 * @param password 密文密码
	 * @return 验证成功返回true
	 */
	public static boolean validatePassword(String plainPassword, String password) {
		String plain = Encodes.unescapeHtml(plainPassword);
		byte[] salt = Encodes.decodeHex(password.substring(0,16));
		System.out.println(StringUtils.join(salt, ""));
		byte[] hashPassword = Digests.sha1(plain.getBytes(), salt, HASH_INTERATIONS);
		return password.equals(Encodes.encodeHex(salt)+Encodes.encodeHex(hashPassword));
	}
	
	/**
	 * 获得活动会话
	 * @return
	 */
	public Collection<Session> getActiveSessions(){
		return sessionDao.getActiveSessions(false);
	}
	
	//-- Role Service --//
	
	public Role getRole(String id) {
		return roleDao.get(id);
	}

	public Role getRoleByName(String name) {
		Role r = new Role();
		r.setName(name);
		return roleDao.getByName(r);
	}
	
	public Role getRoleByEnname(String enname) {
		Role r = new Role();
		r.setEnname(enname);
		return roleDao.getByEnname(r);
	}
	
	public List<Role> findRole(Role role){
		return roleDao.findList(role);
	}
	
	public List<Role> findAllRole(){
		return UserUtils.getRoleList();
	}
	
	@Transactional(readOnly = false)
	public void saveRole(Role role) {
		if (StringUtils.isBlank(role.getId())){
			role.preInsert();
			roleDao.insert(role);
			// 同步到Activiti
			saveActivitiGroup(role);
		}else{
			role.preUpdate();
			roleDao.update(role);
		}
		// 更新角色与菜单关联
		roleDao.deleteRoleMenu(role);
		if (role.getMenuList().size() > 0){
			roleDao.insertRoleMenu(role);
		}
		// 更新角色与部门关联
		roleDao.deleteRoleOffice(role);
		if (role.getOfficeList().size() > 0){
			roleDao.insertRoleOffice(role);
		}
		// 同步到Activiti
		saveActivitiGroup(role);
		// 清除用户角色缓存
		UserUtils.removeCache(UserUtils.CACHE_ROLE_LIST);
//		// 清除权限缓存
//		systemRealm.clearAllCachedAuthorizationInfo();
	}

	@Transactional(readOnly = false)
	public void deleteRole(Role role) {
		roleDao.delete(role);
		// 同步到Activiti
		deleteActivitiGroup(role);
		// 清除用户角色缓存
		UserUtils.removeCache(UserUtils.CACHE_ROLE_LIST);
//		// 清除权限缓存
//		systemRealm.clearAllCachedAuthorizationInfo();
	}
	
	@Transactional(readOnly = false)
	public Boolean outUserInRole(Role role, User user) {
		List<Role> roles = user.getRoleList();
		for (Role e : roles){
			if (e.getId().equals(role.getId())){
				roles.remove(e);
				saveUser(user);
				return true;
			}
		}
		return false;
	}
	
	@Transactional(readOnly = false)
	public User assignUserToRole(Role role, User user) {
		if (user == null){
			return null;
		}
		List<String> roleIds = user.getRoleIdList();
		if (roleIds.contains(role.getId())) {
			return null;
		}
		user.getRoleList().add(role);
		saveUser(user);
		return user;
	}

	//-- Menu Service --//
	
	public Menu getMenu(String id) {
		return menuDao.get(id);
	}

	public List<Menu> findAllMenu(Menu ... menu){
		if(menu.length ==0 || menu[0].getType() == null || menu[0].getType() == 1) return UserUtils.getMenuList();
		else return UserUtils.getMobileMenuList();
	}
	
	@Transactional(readOnly = false)
	public void saveMenu(Menu menu) {
		
		// 获取父节点实体
		menu.setParent(this.getMenu(menu.getParent().getId()));
		
		// 获取修改前的parentIds，用于更新子节点的parentIds
		String oldParentIds = menu.getParentIds(); 
		
		// 设置新的父节点串
		menu.setParentIds(menu.getParent().getParentIds()+menu.getParent().getId()+",");

		// 保存或更新实体
		if (StringUtils.isBlank(menu.getId())){
			menu.preInsert();
			menuDao.insert(menu);
		}else{
			menu.preUpdate();
			menuDao.update(menu);
		}
		
		// 更新子节点 parentIds
		Menu m = new Menu();
		m.setParentIds("%,"+menu.getId()+",%");
		List<Menu> list = menuDao.findByParentIdsLike(m);
		for (Menu e : list){
			e.setParentIds(e.getParentIds().replace(oldParentIds, menu.getParentIds()));
			menuDao.updateParentIds(e);
		}
		// 清除用户菜单缓存
		UserUtils.removeCache(UserUtils.CACHE_MENU_LIST);
//		// 清除权限缓存
//		systemRealm.clearAllCachedAuthorizationInfo();
		// 清除日志相关缓存
		CacheUtils.remove(LogUtils.CACHE_MENU_NAME_PATH_MAP);
	}

	@Transactional(readOnly = false)
	public void updateMenuSort(Menu menu) {
		menuDao.updateSort(menu);
		// 清除用户菜单缓存
		UserUtils.removeCache(UserUtils.CACHE_MENU_LIST);
//		// 清除权限缓存
//		systemRealm.clearAllCachedAuthorizationInfo();
		// 清除日志相关缓存
		CacheUtils.remove(LogUtils.CACHE_MENU_NAME_PATH_MAP);
	}

	@Transactional(readOnly = false)
	public void deleteMenu(Menu menu) {
		menuDao.delete(menu);
		// 清除用户菜单缓存
		UserUtils.removeCache(UserUtils.CACHE_MENU_LIST);
//		// 清除权限缓存
//		systemRealm.clearAllCachedAuthorizationInfo();
		// 清除日志相关缓存
		CacheUtils.remove(LogUtils.CACHE_MENU_NAME_PATH_MAP);
	}
	
	/**
	 * 获取Key加载信息
	 */
	public static boolean printKeyLoadMessage(){
		StringBuilder sb = new StringBuilder();
		sb.append("\r\n======================================================================\r\n");
		sb.append("\r\n    欢迎使用 "+Global.getConfig("productName"));
		sb.append("\r\n======================================================================\r\n");
		System.out.println(sb.toString());
		return true;
	}
	
	///////////////// Synchronized to the Activiti //////////////////
	
	// 已废弃，同步见：ActGroupEntityServiceFactory.java、ActUserEntityServiceFactory.java

	/**
	 * 是需要同步Activiti数据，如果从未同步过，则同步数据。
	 */
	private static boolean isSynActivitiIndetity = true;
	public void afterPropertiesSet() throws Exception {
		if (!Global.isSynActivitiIndetity()){
			return;
		}
		if (isSynActivitiIndetity){
			isSynActivitiIndetity = false;
	        // 同步角色数据
			List<Group> groupList = identityService.createGroupQuery().list();
			if (groupList.size() == 0){
			 	Iterator<Role> roles = roleDao.findAllList(new Role()).iterator();
			 	while(roles.hasNext()) {
			 		Role role = roles.next();
			 		saveActivitiGroup(role);
			 	}
			}
		 	// 同步用户数据
			List<org.activiti.engine.identity.User> userList = identityService.createUserQuery().list();
			if (userList.size() == 0){
			 	Iterator<User> users = userDao.findAllList(new User()).iterator();
			 	while(users.hasNext()) {
			 		saveActivitiUser(users.next());
			 	}
			}
		}
	}
	
	private void saveActivitiGroup(Role role) {
		if (!Global.isSynActivitiIndetity()){
			return;
		}
		String groupId = role.getEnname();
		
		// 如果修改了英文名，则删除原Activiti角色
		if (StringUtils.isNotBlank(role.getOldEnname()) && !role.getOldEnname().equals(role.getEnname())){
			identityService.deleteGroup(role.getOldEnname());
		}
		
		Group group = identityService.createGroupQuery().groupId(groupId).singleResult();
		if (group == null) {
			group = identityService.newGroup(groupId);
		}
		group.setName(role.getName());
		group.setType(role.getRoleType());
		identityService.saveGroup(group);
		
		// 删除用户与用户组关系
		List<org.activiti.engine.identity.User> activitiUserList = identityService.createUserQuery().memberOfGroup(groupId).list();
		for (org.activiti.engine.identity.User activitiUser : activitiUserList){
			identityService.deleteMembership(activitiUser.getId(), groupId);
		}

		// 创建用户与用户组关系
		List<User> userList = findUser(new User(new Role(role.getId())));
		for (User e : userList){
			String userId = e.getLoginName();//ObjectUtils.toString(user.getId());
			// 如果该用户不存在，则创建一个
			org.activiti.engine.identity.User activitiUser = identityService.createUserQuery().userId(userId).singleResult();
			if (activitiUser == null){
				activitiUser = identityService.newUser(userId);
				activitiUser.setFirstName(e.getName());
				activitiUser.setLastName(StringUtils.EMPTY);
				activitiUser.setEmail(e.getEmail());
				activitiUser.setPassword(StringUtils.EMPTY);
				identityService.saveUser(activitiUser);
			}
			identityService.createMembership(userId, groupId);
		}
	}

	public void deleteActivitiGroup(Role role) {
		if (!Global.isSynActivitiIndetity()){
			return;
		}
		if(role!=null) {
			String groupId = role.getEnname();
			identityService.deleteGroup(groupId);
		}
	}

	private void saveActivitiUser(User user) {
		if (!Global.isSynActivitiIndetity()){
			return;
		}
		String userId = user.getLoginName();//ObjectUtils.toString(user.getId());
		org.activiti.engine.identity.User activitiUser = identityService.createUserQuery().userId(userId).singleResult();
		if (activitiUser == null) {
			activitiUser = identityService.newUser(userId);
		}
		activitiUser.setFirstName(user.getName());
		activitiUser.setLastName(StringUtils.EMPTY);
		activitiUser.setEmail(user.getEmail());
		activitiUser.setPassword(StringUtils.EMPTY);
		identityService.saveUser(activitiUser);
		
		// 删除用户与用户组关系
		List<Group> activitiGroups = identityService.createGroupQuery().groupMember(userId).list();
		for (Group group : activitiGroups) {
			identityService.deleteMembership(userId, group.getId());
		}
		// 创建用户与用户组关系
		for (Role role : user.getRoleList()) {
	 		String groupId = role.getEnname();
	 		// 如果该用户组不存在，则创建一个
		 	Group group = identityService.createGroupQuery().groupId(groupId).singleResult();
            if(group == null) {
	            group = identityService.newGroup(groupId);
	            group.setName(role.getName());
	            group.setType(role.getRoleType());
	            identityService.saveGroup(group);
            }
			identityService.createMembership(userId, role.getEnname());
		}
	}

	private void deleteActivitiUser(User user) {
		if (!Global.isSynActivitiIndetity()){
			return;
		}
		if(user!=null) {
			String userId = user.getLoginName();//ObjectUtils.toString(user.getId());
			identityService.deleteUser(userId);
		}
	}
	
	///////////////// Synchronized to the Activiti end //////////////////
	
	
	/**
	 * 根据用户登录名获得所在科室管理员
	 * @param logName
	 * @return
	 */
	public List<String> getDeptManageByLogName(String logName,String roleEnNames){
		User u = userDao.getByLoginName(new User(null,logName));
//		u.setRoleEnames("jzms");
		u.setRoleEnNames(roleEnNames);
		List<User> ulist = userDao.findUserByOfficeId(u);
		List<String> loginNameList = new ArrayList<String>();
		for(User utmp : ulist){
			loginNameList.add(utmp.getLoginName());	
		}
		return loginNameList;
	}
	/**
	 * 字典项数据取值
	 * @param object
	 */
	public void setFieldId(Object object) throws InvocationTargetException, IllegalAccessException {
		if(object instanceof List){
			List os=(List)object;
			if(os.size()>0){
				Class cls=os.get(0).getClass();
				Method[] ms=cls.getDeclaredMethods();
				List<Method> methods=new ArrayList<>();
				for(Method m:ms){
					if(m.getAnnotation(ExcelField.class)!=null && (m.getReturnType()==User.class||m.getReturnType()== ClassGroup.class||m.getReturnType()== Office.class)){
						methods.add(m);
					}
				}
				if(methods.size()>0){
					List<Map<String,String>> list1=userDao.queryUser();
					List<Map<String,String>> list2=classGroupDao.querygroup();
					List<Map<String,String>> list3=officeDao.queryOffice();
					Map<String,String> userMap=getMap(list1);
					Map<String,String> userLoginNameMap=getMap(list1,"loginName");
					Map<String,String> groupMap=getMap(list2);
					Map<String,String> officeMap=getMap(list3);
					for(Object obj:os){
						for(Method method:methods){
							if(method.getReturnType()==User.class){
								User user=(User)method.invoke(obj);
								if(user.getId()==null){
									//当前操作方法的导入导出注解
									ExcelField curField = method.getAnnotation(ExcelField.class); 
									//导出导出字段名
									String exFieldName = curField.value();
									//如果依据loginName查找用户
									if(exFieldName.endsWith("loginName")){
										String id=userLoginNameMap.get(user.getName());
										if(id!=null){
											user.setId(id);
										}else{
											user=null;
										}
									}else{
										user.setId(userMap.get(user.getName()));
									}
									String mthodName = "set"+ org.apache.commons.lang3.StringUtils.substringAfter(method.getName(), "get");
									Reflections.invokeMethod(obj, mthodName, new Class[] {User.class}, new Object[] {user});
								}
							}else if(method.getReturnType()==ClassGroup.class){
								ClassGroup groups=(ClassGroup)method.invoke(obj);
								if(groups.getId()==null){
									groups.setId(groupMap.get(groups.getName()));
									String mthodName = "set"+ org.apache.commons.lang3.StringUtils.substringAfter(method.getName(), "get");
									Reflections.invokeMethod(obj, mthodName, new Class[] {ClassGroup.class}, new Object[] {groups});
								}
							}else if(method.getReturnType()==Office.class){
								Office o=(Office) method.invoke(obj);
								if(o.getId()==null){
									o.setId(officeMap.get(o.getName()));
									String mthodName = "set"+ org.apache.commons.lang3.StringUtils.substringAfter(method.getName(), "get");
									Reflections.invokeMethod(obj, mthodName, new Class[] {Office.class}, new Object[] {o});
								}
							}
						}
					}
				}
			}
		}
	}

	/**
	 * 列表数据转换 成map
	 * @param list
	 * @param keyColumnName 作为键的字段名
	 * @return
	 */
	private Map<String,String> getMap(List<Map<String, String>> list,String ... keyColumnName) {
		Map<String,String> map=new HashMap<>();
		String colName = "name";
		if(keyColumnName.length>0)colName = keyColumnName[0];
		for(Map mmp:list){
			map.put((String)mmp.get(colName),(String) mmp.get("id"));
		}
		return  map;
	}
	/**
	 * 获得当前用户拥有指定权限的角色列表
	 * @param permission
	 * @return
	 */
	public List<Role> getCurUserRoleListByPermission(String permission){
		User user = UserUtils.getUser();
		return roleDao.getCurUserRoleListByPermission(user.getId(), permission);
	}
	
	/**
	 * @param permission
	 * @return 0==仅操作本人数据  1
	 */
	public int getCurUserDataScopeByPermission(String permission){
		// 获得拥有当前菜单角色的最大的数据范围
		User user = UserUtils.getUser();
		List<Role> roles = roleDao.getCurUserRoleListByPermission(user.getId(), permission);
		int scope = 0;
		for (Role r : roles) {
			if (!"8".equals(r.getDataScope())) {
				scope = 1;
			}
		}
		System.out.println(" dataScope is :  " + scope);
		return scope;
	}
	/**
	 * 根据流程名称 获得最新版本在允许的流程定义id
	 * @return
	 */
	public String getprocDefIdByProcDefKey(String procDefKey){
		return actDao.getprocDefIdByProcDefKey(procDefKey);
	}

	/**
	 * 根据流程实例id获取业务id
	 * @param proInsId
	 * @return
	 */
	public String getBusinessIdByProInsId(String proInsId){
		return actDao.getBusinessIdByInsId(proInsId);
	}
	public static void main(String[] args) {
		//System.out.println(SystemService.entryptPassword("123"));
		System.out.println(SystemService.validatePassword("123", SystemService.entryptPassword("123")));
	}

	public Object getRemark(String str) {
		List<String> t=menuDao.getMenuRemark(str);
		if(t.size()>0){
			return t.get(0);
		}
		return "";
	}

	@Transactional(readOnly = false,rollbackFor = Exception.class)
	public void updateOpenId(User user){
		userDao.updateOpenId(user);
	}

    public String checkLoginName(String oldLoginName, String loginName) {
		if (loginName !=null && loginName.equals(oldLoginName)) {
			return "true";
		} else if (loginName !=null && getUserByLoginName(loginName) == null) {
			return "true";
		}
		return "false";
    }
    
    /**
     * 获取组织节点的父节点id
     * @param id
     * @return
     */
    public Office findParentByOfficeId(String id){
    	if(StringUtils.isBlank(id)) return null;
    	Office o = officeDao.get(id);
    	if(o!=null){
    		return o.getParent();
    	}else return null;
    }
    
    public static final String CACHE_CUSTOM_TITLE_MAP = "customTitleMap";
    /**
     * 根据菜单id获得标题定制列表
     * @param menuId
     * @return
     */
    public List<CustomTitle> getCustomTitleByMenuId(String menuId){
    	if(StringUtils.isBlank(menuId))return null;
    	List<CustomTitle> rtn = null;
    	Map<String, List<CustomTitle>> map = null;
    	if(CacheUtils.get(CACHE_CUSTOM_TITLE_MAP)!=null){//缓存
    		map = (Map<String, List<CustomTitle>>) CacheUtils.get(CACHE_CUSTOM_TITLE_MAP);
    		rtn = map.get(menuId);
    	}
    	//缓存中不存在当前菜单id的标题
    	if(rtn == null){//数据库获取
    		rtn = menuDao.getMenuCustomTitleList(menuId);
    		if(map == null) map = new HashMap<>();
    		map.put(menuId, rtn);
    		CacheUtils.put(CACHE_CUSTOM_TITLE_MAP, map);
    	}
    	return rtn;
    }
}
